package com.jingxi.portal.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.jingxi.common.pojo.JingXiResult;
import com.jingxi.common.util.CookieUtils;
import com.jingxi.common.util.HttpClientUtil;
import com.jingxi.common.util.JsonUtils;
import com.jingxi.model.TbItem;
import com.jingxi.portal.pojo.CartItem;

@Service
public class CartServiceImpl implements CartService{

	@Value("${REST_BASE_URL}")
	private String REST_BASE_URL;
	@Value("${ITEM_INFO_URL}")
	private String ITME_INFO_URL;
	
	@Override
	public JingXiResult addCartItem(long itemId, int num, HttpServletRequest request, HttpServletResponse response) {
		//取商品信息
		CartItem cartItem = null;
		//取购物车商品列表
		List<CartItem> itemList = getCartItemList(request);
		//判断购物车商品列表中是否存在此商品
		for(CartItem cItem:itemList) {
			//如果存在商品
			if(cItem.getId() == itemId) {
				//增加商品数量
				cItem.setNum(cItem.getNum() + num);
				cartItem = cItem;
				break;
			}
		}
		
		if(cartItem == null) {
			cartItem = new CartItem();
			//根据商品id查询商品基本信息
			String json = HttpClientUtil.doGet(REST_BASE_URL + ITME_INFO_URL + itemId,null);
			System.out.println("cartjson:" + json);
			//把json转换成java对象
			JingXiResult jingXiResult = JingXiResult.formatToPojo(json,TbItem.class);
			if(jingXiResult!=null && jingXiResult.getStatus() == 200) {
				TbItem item = (TbItem) jingXiResult.getData();
				cartItem.setId(item.getId());
				cartItem.setTitle(item.getTitle());
				cartItem.setImage(item.getImage() == null?"":item.getImage().split(",")[0]);
				cartItem.setNum(num);
				cartItem.setPrice(item.getPrice());
			}
			//添加到购物车列表
			itemList.add(cartItem);
		}
		//把购物车列表写入cookie
		CookieUtils.setCookie(request, response, "TT_CART",JsonUtils.objectToJson(itemList),true);
		return JingXiResult.ok();
	}

	@Override
	public List<CartItem> getCartItemList(HttpServletRequest request) {
		// 从cookie中取商品列表
		String cartJson = CookieUtils.getCookieValue(request, "TT_CART",true);
		if(cartJson == null) {
			return new ArrayList<>();
		}
		//把json转换成商品列表
		try {
			List<CartItem> list = JsonUtils.jsonToList(cartJson, CartItem.class);
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	@Override
	public JingXiResult deleteCartItem(long itemId, HttpServletRequest request, HttpServletResponse response) {
		//从cookie中获取商品列表
		List<CartItem> list = getCartItemList(request);
		for(CartItem cartItem:list) {
			if(cartItem.getId()==itemId) {
				list.remove(cartItem);
				break;
			}
		}
		//处理完毕后重新写入cookie
		CookieUtils.setCookie(request, response, "TT_CART",JsonUtils.objectToJson(list),true);
		return JingXiResult.ok();
	}

}
